Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Difference between [...obj] and {...obj}

I know about the spread operator ... in JavaScript. We can use it on both arrays and objects:

let user = {
  name: "aman",
  rollno: 11
}

let newobj1 = {...user}
let newobj2 = [...user]
console.log(newobj1)
console.log(newobj2)

Why does newobj2 give an error, TypeError: user is not iterable, but newobj1 works fine?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

{...user} just creates a new object with the same properties as user.

[...user], on the other hand, iterates through the object and adds the values it finds into the array it returns. If there is no way to iterate, as there isn't by default on a plain object (as opposed to an array), then this doesn't work and raises the error you've quoted.

As always, there is much more information about this on MDN. Note in particular the following section:

Spread syntax (other than in the case of spread properties) can only be applied to iterable objects like Array, or with iterating functions such as map(), reduce(), and assign().

Many objects are not iterable, including Object:

let obj = {'key1': 'value1'};
let array = [...obj]; // TypeError: obj is not iterable

To use spread syntax with these objects, you will need to provide an iterator function.

And note that the "spread syntax" being referred to here is the "array spread" version. "Object spread" is rather different and explained on this part of the page,

about 4 years ago · Juan Pablo Isaza Report

0

{...user}

means that you create new object and spread all the data from user inside it.

When you suppose to execute

[...user]

you tries to create brand new array and then spread the user object inside.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!